/**
 * Created by zyy on 15/5/27.
 * zhangyuyu@superjia.com
 */
$(function () {
    var preview = {
        init: function (container, options) {
            var self = this
            self.__container = container
            self.__options = options

            var file = options.file
            file.extension = file.suff

            if (App.common.modules.util.isImg(file)) {
                self.img(file)
            } else if (App.common.modules.util.isOffice(file)) {
                self.office(file)
            } else {
                self.invalid(file)
            }
        },

        img: function (file) {
            var self = this
            var container = self.__container
            $.ajax({
                url: '/d/preview/',
                method: 'get',
                dataType: 'json',
                data: {
                    w: '800',
                    linkid: file.linkid
                },
                success: function (data) {
                    if (data.code == 0) {
                        var data = data.data
                        container.html(Mustache.render(imgTpl, {bigimage: data.bigimage}))
                    } else {
                        container.html(Mustache.render(invalidTpl, {
                            message: '对不起，预览失败，请稍后再试。'
                        }))
                    }
                }
            })
        },
        office: function (file) {
            var self = this
            var container = self.__container
            $.ajax({
                url: '/review/file/previewowa/iframe4mobile/',
                method: 'post',
                dataType: 'json',
                data: {
                    linkid: file.linkid
                },
                success: function (data) {
                    if (data.code == 0) {
                        var data = data.data
                        container.html(Mustache.render(officeTpl, {officeUrl: data.downloadurl}))
                    } else {
                        container.html(Mustache.render(invalidTpl, {
                            message: '对不起，预览失败，请稍后再试。'
                        }))
                    }
                }
            })
        },
        invalid: function (file) {
            this.__container.html(Mustache.render(invalidTpl, {
                message: '对不起，移动端不支持此类型文件的预览。'
            }))
        }
    }

    var imgTpl = '<div class="mod-img"><img src="{{bigimage}}" /></div>'
    var officeTpl = '' +
        '<div class="mod-office">' +
        '   <iframe src="{{officeUrl}}" width="100%" height="738px" frameborder="0" background-color="transparent"></iframe>' +
        '</div>'
    var invalidTpl = '' +
        '<div method="post" class="link-form">' +
        '   <p>{{message}}</p>' +
        '</div>'
    preview.init($('.preview'), visitor)
})
